package main;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import control.ControlCommand;
import control.TextButton;

public class MoveImageCanvas extends Canvas{
	MainMidlet midlet;
	TextButton button;
	Image image;
	float x=0;
	float y=0;
	int pX=0;
	int pY=0;
	public MoveImageCanvas(MainMidlet mid,final DrawingCanvas drawingCanvas) {
		this.midlet = mid;
		setFullScreenMode(true);
		this.button = new TextButton("Ok", 10, 360, 120, 30);
		this.button.setCommand(new ControlCommand() {
			public void Do() {
				drawingCanvas.translate(-(int)x, -(int)y);
				midlet.showDrawingCanvas();
			}
		});
		image = drawingCanvas.getImage();
		
	}
	protected void pointerReleased(int x, int y) {
		button.pointerReleased(x, y);
		repaint();
	}
	protected void pointerPressed(int x, int y) {
		pX = x;
		pY = y;
		button.pointerPressed(x, y);
		repaint();
	}

	protected void pointerDragged(int x, int y) {
		if(button.pointerPressed(x, y))
		{
			repaint();
			return;
		}
		this.x += 0.05*(x-pX);
		if(this.x<-image.getWidth()){
			this.x=-image.getWidth();
		}else if(this.x>image.getWidth()){
			this.x=image.getWidth();
		}
		
		this.y += 0.05*(y-pY);
		if(this.y<-image.getHeight()){
			this.y=-image.getHeight();
		}else if(this.y>image.getHeight()){
			this.y=image.getHeight();
		}
		
		pX = x;
		pY = y;
		repaint();
		
	}
	protected void paint(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(0xff222222);
		g.fillRect(0, 0, 240, 400);
		g.setColor(DrawingCanvas.backgroundColor);
		g.fillRect(120-image.getWidth()/2, 200-image.getHeight()/2, image.getWidth(), image.getHeight());
		//g.drawImage(image, 120-image.getWidth()/2+x, 200-image.getHeight()/2+y, 0);
		int drawX = 0;
		int drawY = 0;
		int cropX = 0;
		int cropY = 0;
		int cropW = 0;
		int cropH = 0;
		if(x>0){
			drawX = (int)x;
			cropX = 0;
			cropW = image.getWidth()-(int)x;
		}else{
			drawX = 0;
			cropX = -(int)x;
			cropW = image.getWidth()+(int)x;
		}
		if(y>0){
			drawY = (int)y;
			cropY = 0;
			cropH = image.getHeight()-(int)y;
		}else{
			drawY = 0;
			cropY = -(int)y;
			cropH = image.getHeight()+(int)y;
		}

		g.drawRegion(image, cropX,  cropY, cropW, cropH, 0
				, 120-image.getWidth()/2+drawX, 200-image.getHeight()/2+drawY, 0);
		button.paint(g);
	}

}
